package cn.zzuisa.controller;


import cn.zzuisa.config.TokenManager;
import cn.zzuisa.entity.Invitation;
import cn.zzuisa.entity.Member;
import cn.zzuisa.entity.Reply;
import cn.zzuisa.service.InvitationService;
import cn.zzuisa.service.MemberService;
import cn.zzuisa.service.ReplyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import cn.zzuisa.base.PageRequest;
import cn.zzuisa.base.R;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author frank
 * @since 2019-05-07
 */
@Api(tags = "帖子管理")
@RestController
@RequestMapping("/invitation")
public class InvitationController {

    @Autowired
    InvitationService invitationService;

    @Autowired
    ReplyService replyService;
    @Autowired
    MemberService memberService;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/table1")
    public R<Map<String,Object>> recentSevenData1() {
        List<Integer> count = new ArrayList<>();
        List<LocalDate> days = new ArrayList<>();
        jdbcTemplate.query("SELECT\n" +
                "\tDATE_FORMAT( a.join_time, '%Y-%m-%d' ) days,\n" +
                "\tcount( * ) count \n" +
                "FROM\n" +
                "\t( SELECT * FROM zzu_member WHERE DATE_SUB( CURDATE( ), INTERVAL 7 DAY ) <= date( join_time ) ) AS a \n" +
                "GROUP BY\n" +
                "\tdays", rs -> {
            Map<String,Object> map = new HashMap<>();
            days.add(rs.getDate("days").toLocalDate());
            count.add(rs.getInt("count"));
        });
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("days",days);
        return R.ok(map);
    }

    @GetMapping("/table")
    public R<Map<String,Object>> recentSevenData() {
        List<Integer> count = new ArrayList<>();
        List<LocalDate> days = new ArrayList<>();
        jdbcTemplate.query("SELECT\n" +
                "\tDATE_FORMAT( a.publish_time, '%Y-%m-%d' ) days,\n" +
                "\tcount( * ) count \n" +
                "FROM\n" +
                "\t( SELECT * FROM zzu_invitation WHERE DATE_SUB( CURDATE( ), INTERVAL 7 DAY ) <= date( publish_time ) ) AS a \n" +
                "GROUP BY\n" +
                "\tdays", rs -> {
            Map<String,Object> map = new HashMap<>();
            days.add(rs.getDate("days").toLocalDate());
            count.add(rs.getInt("count"));

        });
        Map<String,Object> map = new HashMap<>();
        map.put("count",count);
        map.put("days",days);
        return R.ok(map);
    }

    // 近七天发帖数量最多的人
    @GetMapping("/table2")
    public R<List<Map<String,Object>>> table2() {
        final List<Map<String,Object>> list = new ArrayList<>();
        jdbcTemplate.query("SELECT\n" +
                "\ta.member_id,\n" +
                "\tcount( * ) count ,\n" +
                "\tb.head_img,\n" +
                "\tb.experience,\n" +
                "\tb.`level`,\n" +
                "\tb.signature,\n" +
                "\tb.name,\n" +
                "\tc.config_value\n" +
                "FROM\n" +
                "\t( SELECT * FROM zzu_invitation WHERE DATE_SUB( CURDATE( ), INTERVAL 7 DAY ) <= date( publish_time ) ) AS a \n" +
                "\tLEFT JOIN zzu_member b ON a.member_id=b.id\n" +
                "\tLEFT JOIN zzu_config c on b.`level` = c.config_name\n" +
                "GROUP BY\n" +
                "\tmember_id\n" +
                "\t",rs->{
            Map<String,Object> map = new HashMap<>();
            map.put("memberId",rs.getLong("member_id"));
            map.put("count",rs.getInt("count"));
            map.put("headImg",rs.getString("head_img"));
            map.put("experience",rs.getInt("experience"));
            map.put("level",rs.getInt("level"));
            map.put("signature",rs.getString("signature"));
            map.put("name",rs.getString("name"));
            map.put("configValue",rs.getString("config_value"));
            list.add(map);
        });
        List<Map<String,Object>> list1 = list.size() > 5 ? list.subList(0,5) : list.subList(0,list.size());
        return R.ok(list1);
    }

    // 添加帖子
    @PostMapping("add")
    public R<Invitation> add(@RequestBody Invitation invitation, HttpServletRequest request) {
        Long userId = TokenManager.get(request.getHeader("token"));
        invitation.setMemberId(userId);

        Member member = memberService.getById(userId);
        int i = member.getExperience();
        int level = member.getLevel();
        // 模块ID不选就是管理员发的 很简陋逻辑
        if(invitation.getModuleId() == null) {
            invitation.setModuleId(-1);
        }
        if(level < 11) {
            if(level * 100 <= i + 30) {
                member.setLevel(level + 1);
                member.setExperience(i + 30 - level * 100);
            }else {
                member.setExperience(i + 30);
            }
            memberService.updateById(member);
        }
        invitation.setPublishTime(LocalDateTime.now());
        invitationService.save(invitation);
        return R.ok(invitation);
    }

    @ApiOperation("已置顶")
    @PutMapping("top")
    public R<String> top(@RequestBody Long[] ids) {
        if(ids == null) {
            return R.error("参数空");
        }
        Arrays.stream(ids).forEach(item -> {
            Invitation invitation = invitationService.getById(item);
            invitation.setIsTop(1);
            invitationService.updateById(invitation);
        });
        return R.ok("已置顶");
    }

    @ApiOperation("取消置顶")
    @PutMapping("untop")
    public R<String> untop(@RequestBody Long[] ids) {
        if(ids == null) {
            return R.error("参数空");
        }
        Arrays.stream(ids).forEach(item -> {
            Invitation invitation = invitationService.getById(item);
            invitation.setIsTop(0);
            invitationService.updateById(invitation);
        });
        return R.ok("已取消置顶");
    }


    // 删除帖子
    @DeleteMapping
    public R<String> remove(Long[] ids) {
        if(ids == null || ids.length < 1) {
            return R.error("参数为空");
        }
        replyService.remove(new QueryWrapper<Reply>().in("invitation_id",ids));
        invitationService.removeByIds(Arrays.asList(ids));
        return R.ok("删除成功");
    }
    // 分页查询所有帖子
    @GetMapping("/page")
    public R<IPage<Map<String,Object>>> page(PageRequest pageRequest, Invitation invitation) {
        IPage<Map<String, Object>> page = new Page<>(pageRequest.getCurrent(), pageRequest.getSize());
        IPage<Map<String,Object>> invitations = invitationService.pageByEntity(page,invitation);
        return R.ok(invitations);
    }

    @GetMapping("/self")
    public R<IPage<Map<String,Object>>> selfPage(PageRequest pageRequest,HttpServletRequest request,Invitation invitation) {
        invitation.setMemberId(TokenManager.get(request.getHeader("token")));
        return page(pageRequest,invitation);
    }

    // 我发的帖子的数量
    @GetMapping("/count")
    public R<Long> countMe(HttpServletRequest request) {
        R<Long> r = new R<>(invitationService.count(
                new QueryWrapper<Invitation>().
                        eq("member_id",request.getSession().getAttribute("user_id"))));
        return r;
    }

    // 查询看某个帖子详情
    @GetMapping("/detail/{id}")
    public R<Map<String,Object>> invitation(@PathVariable Long id) {
        Map<String,Object> map = invitationService.showInvitationById(id);
        Invitation invitation = invitationService.getById(id);
        invitation.setAssessTimes(invitation.getAssessTimes() + 1);
        invitationService.updateById(invitation);
        return R.ok(map);
    }

    @Data
    static class InvitationUpdate {
        private Long id;
        private String title;
        private String content;
    }
    // 修改帖子后返回修改后的内容
    @PutMapping("invitation")
    public R<Map<String,Object>> update(@RequestBody InvitationUpdate invitationUpdate) {
        Invitation invitation = invitationService.getById(invitationUpdate.id);
        invitation.setContent(invitationUpdate.content);
        invitation.setTitle(invitationUpdate.title);
        invitationService.updateById(invitation);
        return R.ok(invitationService.showInvitationById(invitationUpdate.id));
    }

}
